package com.wushijia.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class TestController {

  @RequestMapping(value = {"/auth/user"}, produces = "application/json")
  public Map<String, Object> user(OAuth2Authentication user) {
    Map<String, Object> userInfo = new HashMap<>();
    userInfo.put("user", user.getUserAuthentication().getPrincipal());
    userInfo.put("authorities", AuthorityUtils.authorityListToSet(user.getUserAuthentication().getAuthorities()));
    return userInfo;
  }

  @GetMapping("/product/{id}")
  public String getProduct(@PathVariable String id) {

    //获取当前用户信息，通过调用getContext()返回的对象是SecurityContext接口的实例。这是保存在线程本地存储中的对象
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String username = "";
    if (principal instanceof UserDetails) {
      //多数认证机制以UserDetails为主
      username = ((UserDetails) principal).getUsername();
    } else {
      username = principal.toString();
    }

    //for debug
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return username + " product id : " + id;
  }

  @GetMapping("/order/{id}")
  public String getOrder(@PathVariable String id) {
    //for debug
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return "order id : " + id;
  }


  @RequestMapping("/test0502")
  private void test0502(HttpServletRequest request, HttpServletResponse response) throws IOException {
    System.out.println(getUserField("houyangyang", "name"));
  }

  private String getUserField(String userName, String field) {
    RestTemplate template = new RestTemplate();
    MultiValueMap mvm = new LinkedMultiValueMap<>();
    mvm.add("username", "wenruonan");
    mvm.add("password", "505050");
    mvm.add("scope", "read");
    mvm.add("grant_type", "password");
    mvm.add("client_id", "app50jia");
    mvm.add("client_secret", "50jia123456");
    mvm.add("si", "54978e5207ba373fa76617dc56a2d279b96b0e17");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.set("authorization", "Basic YXBwNTBqaWE6NTBqaWExMjM0NTY=");
    final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(mvm, headers);
    LinkedHashMap userVo = template.postForObject("http://t.50-jia.com/api-user/oauth/token", entity, LinkedHashMap.class);
    String access_token = (String) userVo.get("access_token");
    LinkedHashMap result = template.getForObject("http://t.50-jia.com/api-user/get/userInfo?username=" + userName + "&access_token=" +
            access_token,
        LinkedHashMap.class);
    LinkedHashMap data = (LinkedHashMap) result.get("data");
    return (String) data.get(field);
  }

}